package cn.zyy.hotel.controller.admin;

import cn.zyy.hotel.entity.Orders;
import cn.zyy.hotel.service.OrdersService;
import cn.zyy.hotel.utils.Result;
import cn.zyy.hotel.utils.SystemConstant;
import cn.zyy.hotel.vo.OrdersVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/orders")
public class OrdersAdminController {

    @Resource
    private OrdersService ordersService;

    //查询订单列表
    @RequiresPermissions("order:view")
    @RequestMapping("/list")
    public Result list(OrdersVO ordersVO){
        //设置分页信息
        PageHelper.startPage(ordersVO.getPage(),ordersVO.getLimit());
        //调用查询订单列表的方法
        List<Orders> ordersList = ordersService.selectOrdersList(ordersVO);
        //创建分页对象
        PageInfo<Orders> pageInfo = new PageInfo<Orders>(ordersList);
        return Result.builder().code(0).count(pageInfo.getTotal()).data(pageInfo.getList()).build();
    }

    //确认订单
    @RequiresPermissions("order:confirm")
    @RequestMapping("/confirmOrders")
    public Object confirmOrders(Orders orders){
        Map<String, Object> map = new HashMap<String, Object>();
        //将订单状态改成已确认
        orders.setStatus(2);
        //调用修改订单的方法
        if (ordersService.updateOrders(orders) > 0 ) {
            map.put(SystemConstant.SUCCESS,true);
            map.put(SystemConstant.MESSAGE,"订单确认成功");
        }else {
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"订单确认失败");
        }
        return map;
    }

    //批量确认订单
    @RequiresPermissions("order:batch")
    @RequestMapping("/batchConfirm")
    public Object batchConfirm(String ids){
        Map<String, Object> map = new HashMap<String, Object>();
        int count = 0;
        //将字符串拆分成数组
        String[] idsStr = ids.split(",");
        //循环确认
        for (int i = 0; i < idsStr.length; i++) {
            //创建Orders对象
            Orders orders = new Orders();
            orders.setStatus(2);
            orders.setId(Integer.valueOf(idsStr[i]));
            //调用修改订单的方法
            count = ordersService.updateOrders(orders);
            //判断受影响行数是否大于0
            if (count > 0){
                map.put(SystemConstant.SUCCESS,true);
                map.put(SystemConstant.MESSAGE,"订单确认成功");
            }
        }
        //判断受影响行数是否大于0
        if (count <= 0){
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"订单确认失败");
        }
        return map;
    }



}
